var itemno = "";
var orgcode = "";
var applyid = "";

$(function(){
	
	var applyno = getUrlParam("applyno");
	itemno = getUrlParam("itemno");
	
	if(itemno == '1005'){ // 特殊处理：1005与1002业务一样，by yujunxin 2018/10/21 14:15
		$('#businessForm').load("1002/index.html");
	} else {
		$('#businessForm').load(itemno + "/index.html");
	}

	//获取许可项目的提交材料列表
	getMaterial();

	bindApply(applyno);

	$('#waterway').change(function(){
		var waterwaycode = $(this).val();
		

		bindMark('mark', waterwaycode, null);
	});
})


function bindApply(applyno){
	$.ajax({ 
		url: basePath() + 'business/getapplyinfo.do',
		data: {"applyno": applyno},
		dataType: "json",
        contentType: "application/json",
		success: function(data){
	    	if(data.result == 1){
	    		var jsonApply = data.datas.apply;
	    		var jsonBusiness = data.datas.business;
	    		var jsonMaterial = data.datas.material;
	    		var jsonShip = data.datas.ship;
	    		var jsonCoordinate = data.datas.coordinate;
	    		var jsonDevice = data.datas.device;
	    		
	    		applyid = jsonApply.applyid;
	    		
	    		bindApplyForm(jsonApply);
	    		
	    		//绑定业务资料
	    		bindBusinessForm(jsonBusiness);
	    		
	    		//绑定附件材料
	    		bindMaterialListForm(jsonMaterial);	 
	    	
	    		//绑定证书
	    		bindCertificate(jsonBusiness["recordcertificatelist"]);
	    		
	    		//绑定船舶数据
//	    		bindShipForm(jsonShip);	 
	    		if($('#ship').length > 0){
		    		bindShipForm(jsonShip[0]);
//		    		var src;
//					if(jsonShip[0].verifyresult > 0)
//						src="../img/jiaoyan1.png";
//					else if(jsonShip[0].verifyresult == 0)
//						src="../img/jiaoyan2.png";
//					else
//						src="../img/jiaoyan3.png"
//					$("#shipcheckinfo").html('<img src="'+src+'" alt="" style="width:20px;height:20px;" data-toggle="modal" data-target="#modalCheck" onclick="getVerify(\''+jsonShip[0].shipidnumber+'\')" title="点击查看详情">');
					
	    		}
	    		else{ 
	    			// 水上水下变更需要获取原单数据
	    			try{
	    				if(jsonBusiness['oldapplyno'] != ''){
	    					getoldapplyinfo(jsonBusiness['oldapplyno']);
	    				}
	    			}catch (e) {}
	    			
		    		if(jsonShip != '' && undefined != jsonShip){
		    			for(var i=0; i<jsonShip.length; i++){
		    				var data = jsonShip[i];
		    				bindShipEditList(data);
		    				$("#empty").remove();
		    			}
		    		}
	    		}

	    		//绑定坐标
	    		if(jsonCoordinate != ''){
	    			for(var i=0; i<jsonCoordinate.length; i++){
	    				var data = jsonCoordinate[i];
	    				bindCoordinateList(data);
	    			}
	    		}
	    		//绑定设备
	    		if(undefined != jsonDevice && jsonDevice != ''){
	    			for(var i=0; i<jsonDevice.length; i++){
	    				var data = jsonDevice[i];
	    				if(i == 0){
	    					$('.tr_' + i).find('[name="devicename"]').val(data.devicename);
	    					$('.tr_' + i).find('[name="summary"]').val(data.summary);
	    				} else {
	    					bindDeviceList(data);
	    				}
	    			}
	    		}

	    		//查询文书
//	    		getBookByItemnoAndNodecode(data.datas.nodeno);
	    	}
      	}
	});
}


function bindApplyForm(jsonApply){
	orgcode = jsonApply.orgcode;
	
	$('#orgcode').val(jsonApply.orgcode);
	$('#orgname').val(jsonApply.orgname);
	$('#org').val(jsonApply.orgname);
	$('#org').attr('data', jsonApply.orgcode);
	$('#applyid').val(jsonApply.applyid);
	$('#applyno').val(jsonApply.applyno);
//	$('.applyno').html(jsonApply.applyno);
//	$('.applyno').val(jsonApply.applyno);
//	$('.applyid').val(jsonApply.applyid);
	

	$('[name="itemno"]').val(jsonApply.itemno);
	$('[name="itemname"]').val(jsonApply.itemname);
	$('[name="itemtypecode"]').val(jsonApply.itemtypecode);
	$('#title').html(jsonApply.itemname);
	document.title = jsonApply.itemname;
	
}

function bindBusinessForm(jsonBusiness){
	var waterwaycode = '';
	var markcode = '';
	
	
	for(var d in jsonBusiness){//遍历json对象的每个key/value对,p为key 
		if (d == 'workbegintime' || d == 'workendtime' 
				|| d == 'executionbegintime' || d == 'executionendtime'
				|| d == 'workstarttime' || d == 'worktime' || d == 'destinationporttime'
				|| d == 'ensurebegintime' || d == 'ensureendtime' || d == 'rescuetime'
				|| d == 'delaydate' || d == 'eventtime' || d == 'builddate') {
			$('[name=' + d + ']').val(formatDate(jsonBusiness[d], 'yyyy-mm-dd'));
		}
		else if(d == 'waterwaycode'){
			bindWaterway('waterway', $('#orgcode').val(), jsonBusiness[d]);		
			waterwaycode = jsonBusiness[d];
		}		
		else if(d == 'worktypecode'){
			bindDict('worktypecode', 'DM_SSSXZYLX', jsonBusiness[d]);
		}	
		else if(d == 'workmethodcode'){
			bindDict('workmethodcode', 'DM_SSSXZYFS', jsonBusiness[d]);
		}
		else if(d == 'flagcode'){
			bindDict('flagcode', 'DM_F01_15', jsonBusiness[d]);
		}
		else if(d == 'portcode'){
			bindDict('portcode', 'DM_F01_5', jsonBusiness[d]);
		}
		else if(d == 'markcode'){
			bindDict('markcode', 'DM_F05_10', jsonBusiness[d]);
		}
		else if(d == 'typecode'){
			bindDict('typecode', 'DM_F01_6', jsonBusiness[d]);
		}
		else if(d == 'areacode'){
			bindDict('areacode', 'DM_F01_3', jsonBusiness[d]);
		}
		else if(d == 'sex'){
			bindDict('sex', 'DM_F07_1', jsonBusiness[d]);
		}
		else if(d == 'education'){
			bindDict('education', 'DM_F07_3', jsonBusiness[d]);
		}
		else if(d == 'berthcode'){
			bindBearth('berthcode', orgcode , jsonBusiness[d]);

			if(jsonBusiness[d] == ''){
				$('#other').prop("checked", true);
				$('#otherberth').show();
				$('#otherberth').val(jsonBusiness['berth']);
			}
		}
		else if(d == 'worktype'){
			var worktypes = jsonBusiness[d].split(',');

		    bindDict1('worktype', 'DM_BBZYZL', worktypes);			
		}
		else if(d == 'navigationmarkcode'){
			markcode = jsonBusiness[d];
		}
		else if(d == 'destinationportcode'){
			$('[name=' + d + ']').val(jsonBusiness[d]);
			
	 		var param = {};
	 		param['orgcode'] = jsonBusiness['destinationportorgcode'];
	 		bindPort('destinationportcode', param, jsonBusiness['destinationportcode']);
		}
		else if(d == 'departureportcode'){
			$('[name=' + d + ']').val(jsonBusiness[d]);
			
	 		var param = {};
	 		param['orgcode'] = jsonBusiness['departureportorgcode'];
	 		bindPort('departureportcode', param, jsonBusiness['departureportcode']);
		} 
		else if(d == 'entertime'){
			$('[name=' + d + ']').val(jsonBusiness[d]);
			var entertime = jsonBusiness[d];
			if(entertime != ''){
				$('#leavetime').attr('min', entertime);
			}
		}
		else if (d == 'businesstype'){
			bindDict1('businesstype', 'DM_YTSXLX', jsonBusiness[d]);
		}
		else if (d == 'changetypecode'){
			bindDict1('changetypecode', 'DM_BGLX', jsonBusiness[d]);
		}
		else{
			$('[name=' + d + ']').val(jsonBusiness[d]);
		}
	}
	
	if(waterwaycode != '' && markcode != '')
		bindMark('mark', waterwaycode, markcode);

//	if(getUrlParam('change') == '1' || (jsonBusiness['oldapplyno'] != '' && undefined != jsonBusiness['oldapplyno'])){
//		$('#applytypecode').val('1');
//		$('.applyid').val(applyid);
//
//		$('.change').show();
//
//		document.title += '（变更）';
//		$('#title').html($('#title').html() + '（变更）');
//	}
}


function bindShipForm(jsonShip){
	if(undefined != jsonShip){
		$('#ship').val(jsonShip.shipname);
		$('#ship').attr('data', JSON.stringify(jsonShip));
	}
}

//function bindMaterialListForm(jsonMaterial){
//	for(var i = 0; i < jsonMaterial.length; i++){
////		var ismustsubmit = jsonMaterial[i]['ismustsubmit'];
////		var ismustsubmitStr = "";
////		var must = false;
////		if(ismustsubmit == 1){
////			ismustsubmitStr = '<span style="color:red;">*</span>';
////			must = true;
////		}
//		var index = jsonMaterial[i]['serialnumber'];
////		var quantity = jsonMaterial[i]['quantity'];
////		var materialname = jsonMaterial[i]['materialname'];
//		var fileid=jsonMaterial[i]['fileid'];
//		var fileurl = jsonMaterial[i]['fileurl'];
//		
//		$('#filename_' + index).html(fileurl);
//		$('#upload_' + index).attr('fileid', fileid);
//		
////		$('#' + tableID).find('tbody').append(trStr);
//	}
//}

function getBookByItemnoAndNodecode(nodecode){
	$.ajax({ 
		url: basePath() + 'declare/getnodeparam.do',
		data: {"itemno": itemno, "nodecode": nodecode},
		dataType: "json",
        contentType: "application/json",
		success: function(data){
	    	if(data.result == 1){
	    		var bookcodes = data.datas.bookcode.split(",");
	    		var booknames = data.datas.bookname.split(",");
	    		for(var i = 0; i < bookcodes.length; i++){
	    			var ahtml = '<a target="_blank" href="http://www.baidu.com"><button type="button" class="btn btn-link">'+ booknames[i] +'</button></a>'; 
	    			
	    			$('#book').append(ahtml);
	    		}
	    	}
      	}
	});
}

function bindCertificate(recordcertificatelist){
	if(recordcertificatelist == null || recordcertificatelist == "")
		return ;
	for(var i=0;i<recordcertificatelist.length;i++){
		var html = ''+
		  '	<tr>'+
		  '		<td>'+
		  '			<select class="form-control" name="certificatetype" id="certificatetype'+nowindex+'">'+
		  '		<input type="hidden"  class="form-control" name="recordtype"  value="2"></td>'+
		  '		<td>'+
		  '			<input type="date" class="form-control" name="issuedate" id="issuedate'+nowindex+'">'+
		  '		</td>'+
		  '		<td>'+
		  '			<input type="date" class="form-control" name="effectivedate" id="effectivedate'+nowindex+'">'+
		  '		</td>'+
//		  '		<td>'+
//		  '			是<input type="checkbox" onclick="permanentchange(this)" name="permanent"  value="1" id="permanenty'+nowindex+'">否<input type="checkbox" onclick="permanentchange(this)" name="permanent" checked value="0" id="permanentn'+nowindex+'">'+
//		  '		</td>'+
		  '		<td id="filename'+ nowindex +'"></td>'+
		  '	    <td><button type="button"  onclick="openModal('+nowindex+')" class="btn btn-success" ><span class="glyphicon glyphicon-upload"></span>上传</button>'+
		  '			<input type="hidden" id="upload'+nowindex+'" class="form-control" name="fileid"  value=""></td>'+
		  '		<td>'+
		  '			<button type="button"  onclick="deleterecordcertificate(this)" class="btn btn-danger btn-sm" style="margin-right:10px;"><span class="glyphicon glyphicon-minus"></span></button>'+
		  '		</td>'+
		  '	</tr>';	
		
		$("#recordcertificate").find('tbody').append(html);
		bindDict("certificatetype"+nowindex,"DM_DWBAZSLX",recordcertificatelist[i]["certificatetype"],null,null);
		$("#issuedate"+nowindex).val( formatDate(recordcertificatelist[i]["issuedate"], 'yyyy-mm-dd'));
		$("#effectivedate"+nowindex).val( formatDate(recordcertificatelist[i]["effectivedate"], 'yyyy-mm-dd'));
		
		for(var j=0;j<recordcertificatelist[i]["recordcertificatefile"].length;j++){
	        var filename = '<p id="'+ recordcertificatelist[i]["recordcertificatefile"][j]["FILEID"] +'"><a href="/gahCSP/share/downFiles.do?filename='+ recordcertificatelist[i]["recordcertificatefile"][j]["FILENAME"] +'&fileid='+ recordcertificatelist[i]["recordcertificatefile"][j]["FILEID"] +'">' + recordcertificatelist[i]["recordcertificatefile"][j]["FILENAME"] + '</a><span class="glyphicon glyphicon-remove" style="color:red;cursor:pointer;" onclick="deleteFile(\''+ nowindex +'\', \''+ recordcertificatelist[i]["recordcertificatefile"][j]["FILEID"] +'\')"></span></p>';
	        var fileids=$('#upload' + nowindex).val();
	        if(fileids==""){
	        	fileids+=recordcertificatelist[i]["recordcertificatefile"][j]["FILEID"];
	        }else{
	         	fileids += ',' + recordcertificatelist[i]["recordcertificatefile"][j]["FILEID"];
	         }
			$("#filename"+nowindex).append(filename);
	        $('#upload' + nowindex).attr("value", fileids);

		}
		
		
		nowindex++;
		
		
		
		
		
		
		
//		var html='	<tr>'+
//		  '		<td>'+
//		  recordcertificatelist[i]["certificatetypename"]+
//		  '		</td>'+
//		  '		<td>'+
//		  formatDate(recordcertificatelist[i]["issuedate"])	+
//		  '		</td>'+
//		  '		<td>'+
//		  formatDate(recordcertificatelist[i]["effectivedate"])	+
//		  '		</td>'+
//		  '		<td id="filename'+ recordcertificatelist[i]["certificateid"]+'"></td>'+
//		  '	</tr>';	
//		$("#recordcertificate").find('tbody').append(html);
//		
//		
	}
}

function getoldapplyinfo(oldapplyno){
	$.ajax({ 
		url: basePath() + 'business/getapplyinfo.do',
		data: {"applyno": oldapplyno},
		dataType: "json",
        contentType: "application/json",
		success: function(data){
	    	if(data.result == 1){
				var jsonShip = data.datas.ship;

				if (jsonShip != '' && undefined != jsonShip) {
					for (var i = 0; i < jsonShip.length; i++) {
						var data = jsonShip[i];
						try {
							bindShipListBefore(data);
						} catch (e) {
							console.log(e);
						}
					}
				}
	    	}
      	}
	});
}